import java.io.IOException;
import java.net.*;
import java.util.*;

public class UdpSocketClient {
    private DatagramSocket socket = null;
    private  String serverIP;
    private int serverPort;

    public UdpSocketClient(String serverIP, int  serverPort) throws SocketException {
        socket = new DatagramSocket(); // 客户端的话，无参数代表随机端口号~~
        this.serverIP = serverIP;
        this.serverPort = serverPort;
    }

    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.println("->");
            String request = scanner.next();

            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                    InetAddress.getByName(serverIP), serverPort);
            socket.send(requestPacket);
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            System.out.printf("rep: %s, resp: %s\n", request, response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpSocketClient udpSocketClient = new UdpSocketClient("127.0.0.1", 8090);
        udpSocketClient.start();
    }
}
